﻿using System;
using System.Drawing.Imaging;
using Microsoft.Xna.Framework;

namespace ThreeDContentPipeline
{
    public class SpriteFontContent
    {
        public SpriteFontContent(string file)
        {
            int ulc, lrc, bgc, i = 0, j = 0;
            Rectangle[] temp;
            byte[] pixels;

            Image = new BitmapImage(file);
            Image.Convert(ImageFormat.Png);

            pixels = Image.UnZip();

            ulc = PackColor(0, 0, pixels);
            lrc = PackColor(1, 0, pixels);
            bgc = PackColor(2, 0, pixels);

            UnpackColor(1, 0, bgc, pixels);

            Rectangles = new Rectangle[512];

            for (int y = 0; y != Image.Height; y++)
                for (int x = 0; x != Image.Width; x++)
                {
                    int c = PackColor(x, y, pixels);

                    if (c == ulc)
                    {
                        Rectangles[i++] = new Rectangle(x, y, 0, 0);

                        UnpackColor(x, y, bgc, pixels);
                    }
                    else if (c == lrc)
                    {
                        Rectangle r = Rectangles[j];

                        r.Width = x - r.X;
                        r.Height = y - r.Y;
                        Rectangles[j++] = r;

                        UnpackColor(x, y, bgc, pixels);
                    }
                    else if (c == bgc)
                        UnpackColor(x, y, bgc, pixels);
                }
            temp = new Rectangle[j];
            Array.Copy(Rectangles, temp, j);
            Rectangles = temp;

            Image.Zip(pixels);
        }

        public Rectangle[] Rectangles
        {
            get;
            set;
        }

        public BitmapImage Image
        {
            get;
            set;
        }

        private int PackColor(int x, int y, byte[] pixels)
        {
            int i = y * Image.Width * 4 + x * 4;
            int r = pixels[i++];
            int g = pixels[i++];
            int b = pixels[i++];

            return (r << 16) | (g << 8) | b;
        }

        private void UnpackColor(int x, int y, int c, byte[] pixels)
        {
            int i = y * Image.Width * 4 + x * 4;
            int r = (c >> 16) | 0xff;
            int g = (c >> 8) | 0xff;
            int b = c | 0xff;
            int a = 0;

            pixels[i++] = (byte)r;
            pixels[i++] = (byte)g;
            pixels[i++] = (byte)b;
            pixels[i++] = (byte)a;
        }
    }
}
